package cn.ulc.store.amiExt;

import cn.ulc.common.util.ConvertUtil;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.mapper.MapperInvoke;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class SaveAmiExt implements MapperInvoke {
    public SaveAmiExt() {
    }

    @Override
    public Object call(SQLManager sqlManager, Class aClass, String s, Method method, Object[] objects) {
//        BaseModel baseModel = (BaseModel) objects[0];
        if(objects == null || objects[0] == null) return null;
        Field[] fields = aClass.getFields();
        Long id = 0l;
        try {
            for(int i = 0; i < fields.length; i++){
                if("id".equals(fields[i].getName())){
                    Field subField = fields[i];
                    subField.setAccessible(true);
                    Object o = subField.get(objects[0]);
                    id = ConvertUtil.toLong(o);
                    break;
                }
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(id <= 0) {
            return sqlManager.insert(aClass,objects[0],true);
        }else {
            return sqlManager.updateTemplateById(aClass,objects[0]);
        }
    }
}
